﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AccessDb;
using QQ.Util;

namespace SoftwareManager
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 定义更目录
        /// </summary>
        private static string rootpath = Application.StartupPath;//根目录
        /// <summary>
        /// 定义数据库的位置
        /// </summary>
        private string dbpath = rootpath + "\\DB.mdb";

        private string userlist = rootpath + "\\人员名单.txt";
        private string softwareList = rootpath + "\\软件名单.txt";

        public MainForm()
        {
            InitializeComponent();
            this.skinEngine1.SkinFile = "skin\\Longhorn.ssk";
            this.skinEngine1.SkinAllForm = true;
            this.skinEngine1.Active = true;
            //=========注册右键事件=========
            this.data_machine.ContextMenuStrip = this.CreateContextMenu();
            this.data_machine.ContextMenuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStrip_ItemClicked);
            this.data_machine.ContextMenuStrip.Paint += new System.Windows.Forms.PaintEventHandler(this.contextMenuStrip_Paint);
            searchMachine();

            //读取姓名和软件名称
            List<string> user = TextBoxTools.getFileList(userlist);
            List<string> soft = TextBoxTools.getFileList(softwareList);
            foreach (string tem in user)
            {
                cb_username.Items.Add(tem);
            }
            foreach (string str in soft)
            {
                cb_softName.Items.Add(str);
            } 
        }
         

        /// <summary>
        /// 创建右键菜单
        /// </summary>
        /// <returns></returns>
        private ContextMenuStrip CreateContextMenu()
        {
            System.Windows.Forms.ContextMenuStrip contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
            System.Windows.Forms.ToolStripMenuItem menu_1 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_2 = new System.Windows.Forms.ToolStripMenuItem();
            System.Windows.Forms.ToolStripMenuItem menu_3 = new System.Windows.Forms.ToolStripMenuItem();

            System.Windows.Forms.ToolStripSeparator toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            // 
            // contextMenuStrip1
            // 
            contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { menu_1, menu_2, menu_3, toolStripSeparator1 });
            contextMenuStrip.Name = "contextMenuStrip1";
            contextMenuStrip.Size = new System.Drawing.Size(153, 120);

            menu_1.Enabled = true;
            menu_1.Name = "new";
            menu_1.Size = new System.Drawing.Size(152, 22);
            menu_1.Text = "添加     ";

            menu_2.Enabled = false;
            menu_2.Name = "modify";
            menu_2.Size = new System.Drawing.Size(152, 22);
            menu_2.Text = "修改     ";

            menu_3.Enabled = false;
            menu_3.Name = "delete";
            menu_3.Size = new System.Drawing.Size(152, 22);
            menu_3.Text = "刪除     ";


            return contextMenuStrip;
        }



        private void contextMenuStrip_Paint(object sender, PaintEventArgs e)
        {
            if (sender is System.Windows.Forms.ContextMenuStrip)
            {
                bool IsSelected = this.data_machine.SelectedRows.Count == 1 ? true : false;
                ContextMenuStrip contextMenuStrip = ((System.Windows.Forms.ContextMenuStrip)sender);
                foreach (ToolStripItem item in contextMenuStrip.Items)
                {
                    item.Enabled = (item.Name == "edit" || item.Name == "del") ? IsSelected : true;
                }
            }
        }


        /// <summary>
        /// 右键菜单元素单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStrip_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
        {
            try
            {
                DataGridViewRow row = null;
                if (this.data_machine.SelectedRows.Count == 1)
                {
                    row = this.data_machine.SelectedRows[0];
                }
                if ("new" == e.ClickedItem.Name)
                {
                    AddForm af = new AddForm();
                    af.ReturnHandler += new Action<bool>(delegate(bool succ)
                    {
                        if (succ == true)
                        {
                            searchMachine();
                        }
                    });
                    af.ShowDialog();
                }
                else if ("modify" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        AddForm af = new AddForm();
                        af.ID=   row.Cells["id"].Value.ToString();

                        af.ReturnHandler += new Action<bool>(delegate(bool succ)
                        {
                            if (succ == true)
                            {
                                searchMachine();
                            }
                        });
                        af.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("請先點擊某一行的開頭，再右鍵進行操作！");
                    }
                }
                else if ("delete" == e.ClickedItem.Name)
                {
                    if (row != null)
                    {
                        string id = row.Cells["id"].Value.ToString();

                        DialogResult dr = MessageBox.Show("您確認刪除該項！刪除后不可恢復哦！？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dr == DialogResult.Yes && id != "")
                        {
                          bool result=  delMachine(id);
                          if (result == true)
                          {
                              MessageBox.Show("恭喜删除成功！");
                              searchMachine();//重新搜索一下数据！代表刷新一下数据

                          }
                          else
                          {
                              MessageBox.Show("很遺憾！刪除數據出錯了");
                          }

                        }
                       
                        
                    }
                    else
                    {
                        MessageBox.Show("請先點擊某一行的開頭，再右鍵進行操作！");
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }







        /// <summary>
        /// 删除机器码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool delMachine(string id)
        {
            string sql = string.Format("delete from machine where id={0}",id);

            AccessDbClass au = new AccessDbClass(dbpath);
            bool result=au.ExecuteSQLNonquery(sql);
            au.Close();

            return result;
        }


        private void searchMachine()
        {
            string softname = cb_softName.Text;
            string username = cb_username.Text;
            string machinecode = txt_machineCode.Text;

            string sql = "SELECT * FROM machine WHERE 1=1";

            if (softname.Trim() != "")
            {
                sql = sql + " and softname like '%" + softname + "%'";
            }
            if (username.Trim() != "")
            {

                sql = sql + " and username='" + username + "'";
            }

            if (machinecode.Trim() != "")
            {
                sql = sql + " and machinecode like '%" + machinecode + "%'";
            }

            while (this.data_machine.Rows.Count != 0)
            {
                this.data_machine.Rows.RemoveAt(0);
            }
            AccessDbClass au = new AccessDbClass(dbpath);
            data_machine.DataSource = au.SelectToDataSet(sql, "machine").Tables[0].DefaultView;
            au.Close();

        }



        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_search_Click(object sender, EventArgs e)
        {
            searchMachine();//搜索机器码
        }
    }
}
